package com.example.parking.application;

import com.example.parking.domain.model.ParkingLot;
import com.example.parking.domain.repository.ParkingLotRepository;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.OffsetDateTime;
import java.util.List;

@Service
public class ParkingLotService {
    private final ParkingLotRepository parkingLotRepository;

    public ParkingLotService(ParkingLotRepository parkingLotRepository) {
        this.parkingLotRepository = parkingLotRepository;
    }

    @Cacheable(cacheNames = "lots:all")
    public List<ParkingLot> listAll() {
        return parkingLotRepository.findAll();
    }

    public ParkingLot getById(Long id) {
        return parkingLotRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("lot not found"));
    }

    @Transactional
    @CacheEvict(cacheNames = {"lots:all"}, allEntries = true)
    public ParkingLot create(ParkingLot lot) {
        if (parkingLotRepository.existsByCode(lot.getCode())) {
            throw new IllegalArgumentException("lot code exists");
        }
        lot.setCreatedAt(OffsetDateTime.now());
        lot.setUpdatedAt(OffsetDateTime.now());
        return parkingLotRepository.save(lot);
    }

    @Transactional
    @CacheEvict(cacheNames = {"lots:all"}, allEntries = true)
    public ParkingLot update(Long id, ParkingLot incoming) {
        ParkingLot lot = getById(id);
        lot.setName(incoming.getName());
        lot.setAddress(incoming.getAddress());
        lot.setTotalSpaces(incoming.getTotalSpaces());
        lot.setAvailableSpaces(incoming.getAvailableSpaces());
        lot.setUpdatedAt(OffsetDateTime.now());
        return parkingLotRepository.save(lot);
    }

    @Transactional
    @CacheEvict(cacheNames = {"lots:all"}, allEntries = true)
    public void delete(Long id) {
        parkingLotRepository.deleteById(id);
    }
}


